import storage from 'store'
import expirePlugin from 'store/plugins/expire'
import { login, logout } from '@/api/login'
import { minePermission } from '@/api'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { welcome } from '@/utils/util'

storage.addPlugin(expirePlugin)
const user = {
  state: {
    token: '',
    name: '',
    avatar: '',
    welcome: '',
    roles: [],
    info: {
      role: {
        permissions: [{
          permissionId: 'dashboard',
          permissionName: '仪表盘'
        }]
      }
    },
    loginInfo: {},
    hasPassword: false
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_INFO: (state, info) => {
      state.info = info
      try {
        const loginInfo = JSON.parse(localStorage.getItem('loginInfo'))
        state.info['name'] = loginInfo.customer_info.fullname
        state.info['username'] = loginInfo.customer_info.nickname
        state.info['mobile'] = loginInfo.customer_info.mobile
        state.info['customer_id'] = loginInfo.customer_id
        state.info['town_id'] = loginInfo.town_id
        state.info['lastLoginTime'] = loginInfo.timeout
        state.hasPassword = loginInfo.has_password
        state.welcome = welcome()
      } catch (e) {
        // TODO handle the exception
      }
    },
    SET_LOGIN_INFO: (state, info) => {
      localStorage.setItem('loginInfo', JSON.stringify(info))
      state.loginInfo = info
    }
  },

  actions: {
    // 登录
    Login ({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo).then(result => {
          storage.set(ACCESS_TOKEN, result.token, new Date().getTime() + 7 * 24 * 60 * 60 * 1000)
          commit('SET_TOKEN', result.token)
          commit('SET_LOGIN_INFO', result)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo ({ commit, state }) {
      return new Promise((resolve, reject) => {
         minePermission().then(res => {
           res.list && res.list.forEach(v => {
             state.info.role.permissions.push({
               permissionId: v.name,
               permissionName: v.display_name
             })
             v.child_permission && v.child_permission.forEach(u => {
               state.info.role.permissions.push({
                 permissionId: u.name,
                 permissionName: u.display_name,
                 actionEntitySet: u.child_permission && u.child_permission.map(t => {
                   const arr = t.name.split('.')
                   return {
                     action: arr[arr.length - 1],
                     describe: t.display_name,
                     defaultCheck: false
                   }
                 })
               })
             })
           })
           if (state.info.role && state.info.role.permissions.length > 0) {
             const role = { ...state.info.role }
             role.permissions = state.info.role.permissions.map(permission => {
               const per = {
                 ...permission,
                 actionList: (permission.actionEntitySet || []).map(item => item.action)
                }
               return per
             })
             role.permissionList = role.permissions.map(permission => { return permission.permissionId })
             // 覆盖响应体的 role, 供下游使用
             state.info.role = role
             commit('SET_ROLES', role)
             commit('SET_INFO', state.info)
             // 下游
             resolve(state.info)
           } else {
             reject(new Error('getInfo: roles must be a non-null array !'))
           }
         }).catch(error => {
           reject(error)
         })
      })
    },

    // 登出
    Logout ({ commit, state }) {
      return new Promise((resolve) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_INFO', {
            role: {
              permissions: [{
                permissionId: 'dashboard',
                permissionName: '仪表盘'
              }]
            }
          })
          commit('SET_LOGIN_INFO', {})
          storage.remove(ACCESS_TOKEN)
          resolve()
        }).catch((err) => {
          console.log('logout fail:', err)
          // resolve()
        }).finally(() => {
        })
      })
    }

  }
}

export default user
